package com.profgj.profgj.service.impl;

import com.profgj.profgj.entity.Role;
import com.profgj.profgj.entity.User;
import com.profgj.profgj.service.RoleService;
import com.profgj.profgj.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理用户登录数据库查询过程
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    /**
     * 用户服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 用户角色服务对象
     */
    @Resource
    private RoleService roleService;

    /**
     * 用户名查询用户和角色
     * @param userName  用户名
     * @return  SpringSecurity识别的认证对象
     * @throws UsernameNotFoundException    用户名没有找到异常类
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        // 用户名查询用户数据库
        User user = userService.queryUserByName(userName);
        // 用户id查询用户角色
        Role role = roleService.queryById(user.getRoleId());
        // 用户和角色 转换UserDetails对象
        return changeToUser(user, role);
    }


    /**
     * 用户和角色 转换UserDetails对象
     * @param user  用户
     * @param role  角色
     * @return
     */
    private UserDetails changeToUser(User user, Role role) {

        // 授权List
        List<GrantedAuthority> authorityList = new ArrayList<>();
        // 创建授权对象
        GrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
        // 加入到集合中
        authorityList.add(authority);
        // 使用用户名密码和角色 和 授权list 创建UserDetails对象
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorityList);
        // 返回
        return userDetails;
    }


}
